import React, { useEffect } from "react";
import { useSelector } from "react-redux";
import { RootState } from "../../store";
import {
  Flex,
  Checkbox,
  ProductCard,
  Stepper,
  SwipeCell,
  Button,
  SubmitBar,
} from "react-vant";
import { useDispatch } from "react-redux/es/exports";
import { useNavigate } from "react-router-dom";
const Car = () => {
  // 获取购物车数据
  const carList = useSelector((state: RootState) => state.car.carList);
  // 总价钱: 选中数据
  const totalPrice = carList.reduce((p, n) => {
    return n.isChecked ? p + n.count * n.price : p;
  }, 0);
  // 全选状态
  const isAllCheck = carList.every((v) => v.isChecked);
  const navigate = useNavigate();
  const dispatch = useDispatch();

  return (
    <div>
      <div>
        {carList.map((v) => {
          return (
            <SwipeCell
              key={v.id}
              rightAction={
                <Button
                  type="danger"
                  style={{ height: "100%" }}
                  onClick={() => dispatch({ type: "deleteCar", payload: v })}
                >
                  删除
                </Button>
              }
            >
              <Flex align="center" justify="center">
                <Flex.Item span={2}>
                  <Checkbox
                    checked={v.isChecked}
                    onChange={() => dispatch({ type: "switchCar", payload: v })}
                  ></Checkbox>
                </Flex.Item>
                <Flex.Item span={22}>
                  <ProductCard
                    num={
                      <Stepper
                        defaultValue={v.count}
                        min={1}
                        onMinus={() => dispatch({ type: "subCar", payload: v })}
                        onPlus={() => dispatch({ type: "addCar", payload: v })}
                      ></Stepper>
                    }
                    price={v.price.toFixed(2)}
                    desc={v.word}
                    title={v.title}
                    thumb={v.image}
                  ></ProductCard>
                </Flex.Item>
              </Flex>
            </SwipeCell>
          );
        })}
      </div>

      <SubmitBar
        price={totalPrice * 100}
        buttonText="提交订单"
        onSubmit={() => navigate("/order", { state: { price: totalPrice } })}
      >
        <Checkbox
          checked={isAllCheck}
          onChange={(checked) =>
            dispatch({ type: "switchAllCar", payload: checked })
          }
        >
          全选
        </Checkbox>
      </SubmitBar>
    </div>
  );
};

export default Car;
